import axios from "axios";
import router from "@/router/index";
import { message } from "./resetMessage";
//import { Loading } from "element-ui";

// 环境的切换
if (process.env.NODE_ENV == "development") {
    // 开发环境!
    axios.defaults.baseURL = "http://192.168.0.152:7001";
} else if (process.env.NODE_ENV == "devlopment_test") {
    // 测试环境!
    axios.defaults.baseURL = "https://192.168.0.145:9001";
} else if (process.env.NODE_ENV == "production") {
    // 上线环境!
    axios.defaults.baseURL = "https://channel.xssbdc.com/record";
}

const myRequire = {};

// 插件必须提供一个install方法
myRequire.install = function(Vue) {
    // 给vue实例添加一个成员$http
    // axios.defaults.baseURL = "http://192.168.0.131:9001";
    //测试ip192.168.0.135
    //正毅：172.27.252.222 172.27.132.116
    //正式;https://yun.xssbdc.com/api http://47.108.54.171/api
    //设置请求超时
    axios.defaults.timeout = 10000;
    //让ajax携带cookie
    //axios.defaults.withCredentials = true;
    //post请求头设置
    axios.defaults.headers.post["Content-Type"] =
        "application/json;charset=UTF-8";
    axios.defaults.headers.put["Content-Type"] = "application/json;charset=UTF-8";
    //"application/x-www-form-urlencoded;charset=UTF-8";
    // 设置axios拦截器
    // 添加请求拦截器.发送请求之前判断当前是否是登陆，是就不设置token
    axios.interceptors.request.use(
        function(config) {
            // 在发送请求之前设置请求头
            if (config.url.toLocaleLowerCase() !== "/login") {
                let token = localStorage.getItem("token");
                // config.headers.Authorization = token;
                config.headers.CHANNEL_TOKEN = token;
            }
            return config;
        },
        function(error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        }
    );
    // 添加响应拦截器
    axios.interceptors.response.use(
        function(response) {
            // 对响应数据做点什么
            // 判断获取数据是否成功
            let code = response.data.code;
            let msg = response.data.message;
            if (response.status == 401) {
                router.push({ path: "/" });
                localStorage.clear();
                sessionStorage.clear();
                message.error("登录过期，请重新登录！！！");
            }
            if (code == 530) {
                message.error(msg);
                router.push({ path: "/" });
                localStorage.clear();
                sessionStorage.clear();
            } else if (code != 200 && code) {
                message.error(msg);
            }
            return response;
        },
        function(error) {
            console.log(111);
            // 对响应错误做点什么
            if (error && error.response) {
                switch (error.response.status) {
                    case 400:
                        error.message = "请求错误";
                        break;
                    case 401:
                        error.message = "登录校验失败，请重新登录";
                        break;
                    default:
                        error.message = `链接错误 ${error.response.status}`;
                }
            } else {
                error.message = "网络出现问题，请稍后再试";
            }
            return Promise.reject(error);
        }
    );
    // 配置全局axios
    // Vue.prototype.$http = axios;
    //添加vue实例方法，供所有组件使用
    Vue.prototype.startLoading = function() {
        const loading = this.$loading({
            lock: true,
            text: "数据加载中",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)"
        });
        return loading;
    };
    Vue.prototype.closeLoading = function(loading) {
        setTimeout(() => {
            loading.close();
        }, 200);
    };
};
// 导出成员
export default myRequire;

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                params: params
            })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err);
            });
    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .post(url, params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err);
            });
    });
}

/**
 * put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function put(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .put(url, params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err);
            });
    });
}

/**
 * delete方法，对应delete请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function fdelete(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .delete(url, params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err);
            });
    });
}